【前言】
終於要來到倒數幾篇了!!!有沒有對於這些更熟悉了呢?希望有幫到大家!
【正文】
今天來介紹<Redirect>
吧!
<Redirect>
:用來轉址,會覆蓋目前的history stacktrue
,不會改寫路徑,而是直接在目前的history增加新的entry<Switch>
<Redirect from='/old-path' to='/new-path'/>
<Route path='/new-path' component={Place}/>
</Switch>
withRouter
:一個HOC,可以把match、location、history當成props傳入component中import React from "react";
import PropTypes from "prop-types";
import { withRouter } from "react-router";
class ShowTheLocation extends React.Component {
// 將match、location、history當成props傳入ShowTheLocation組件,可以讓原本沒有接收props或是state的component能夠因為location的改變而render
static propTypes = {
match: PropTypes.object.isRequired,
location: PropTypes.object.isRequired,
history: PropTypes.object.isRequired
};
render() {
const { match, location, history } = this.props;
return <div>You are now at {location.pathname}</div>;
}
}
const ShowTheLocationWithRouter = withRouter(ShowTheLocation);
export default ShowTheLocationWithRouter;